<?
include('../../initDB.php');
include('../../configuration.php');
include('../../querys.php');

session_start();
if ( $_SESSION['log']== TRUE)
	exit(); 	

$error_messages = array(
	0 => "error: registration failed.",
	1 => "error: passwords don't match.",
	2 => "error: that user name already exists",
	3 => "error: that email is already registered",
	4 => "error: there was a problem connecting to the database",
	5 => "error: not enough data",								
	6 => "success: registration successfull",				
	// client-side should do some data validation: only sends form if all fields are filled
	);
	
$errors = array();
$response['registration']['code'] = array();
$response['registration']['message'] = array();

if( !(isset($_POST['user']) && isset($_POST['pass']) &&
	 isset($_POST['pass2']) && isset($_POST['email'])&&
	 isset($_POST['birth']))) {
		array_push($errors, 5);
	 }
				 
$user = $_POST['user'];
$pass = $_POST['pass'];
$pass2 = $_POST['pass2'];
$email = $_POST['email'];
$birth = $_POST['birth'];

if ($pass != $pass2)
	array_push($errors, 1);

# insert user
# <N pode haver user igual>

if (!sizeof($errors)) {

	$retrieveUser->execute(array($user));
	$result = $retrieveUser->fetch(PDO::FETCH_OBJ);
	if ($result != FALSE) {
		$counter = count($result->fetchAll());
		if ($counter != 0)
		array_push($errors, 2);	
	}
		
	$retrieveUserfromEmail->execute(array($email));
	$result = $retrieveUserfromEmail->fetch(PDO::FETCH_OBJ);
	if ($result != FALSE) {
		$counter = count($result->fetchAll());
		if ($counter != 0)
		array_push($errors, 3);	
	}
	
	if (!sizeof($errors)) {
	
		$userInsert->execute(array(NULL, $user, $email, $birth));
		$retrieveUser->execute(array($user));							# retrieve id
		$result = $retrieveUser->fetch(PDO::FETCH_OBJ);
		$passwordInsert->execute(array(NULL, $result->id, md5($pass))); # Password should be already hashed
		
		array_push($response['registration']['code'], 6);
		array_push($response['registration']['message'], $error_messages[6]);
	}
}

if (sizeof($errors)) {
	
	array_push($response['registration']['code'], 0);
	array_push($response['registration']['message'], $error_messages[0]);
	
	foreach ($errors as $code) {
		array_push($response['registration']['code'], $code);
		array_push($response['registration']['message'], $error_messages[$code]);
	}
}
	
print_output($response);

?>